package com.example.de.vogella.android.locationapi.simple;

//import android.view.Menu;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
//import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
//import android.renderscript.Element;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class ShowLocationActivity extends Activity implements LocationListener {

	private TextView latituteField;
	private TextView longitudeField;
	private TextView GPSSpeedField;
	private TextView AccuracyField;
	private TextView OSMSpeedField;
	private LocationManager locationManager;

	// private String provider;

	// PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
	// PowerManager.WakeLock wl =
	// pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");

	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.e("GPS", "onCreate started...");
		super.onCreate(savedInstanceState);

		
		
		Log.e("GPS", "getOSMSpeed before...");
		AndroidXMLParsingActivity parser = new AndroidXMLParsingActivity();
		parser.doInBackground();//getOSMSpeed();
		Log.e("GPS", "getOSMSpeed after...");
		
		// wl.acquire();
		// getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
		// this.getWindow().setFlags(this.getWindow().getFlags() &
		// ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		this.getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		setContentView(R.layout.activity_show_location);
		latituteField = (TextView) findViewById(R.id.Latitude);
		longitudeField = (TextView) findViewById(R.id.Longitude);
		GPSSpeedField = (TextView) findViewById(R.id.GPSSpeed);
		AccuracyField = (TextView) findViewById(R.id.Accuracy);
		OSMSpeedField = (TextView) findViewById(R.id.OSMSpeed);

		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the location provider -> use
		// default
		// Criteria criteria = new Criteria();
		// provider = locationManager.getBestProvider(criteria, false);
		// Location location = locationManager.getLastKnownLocation(provider);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				400, 1, this);

		// Initialize the location fields
		// if (location != null) {
		// System.out.println("Provider " + provider + " has been selected.");
		// onLocationChanged(location);
		// } else {
		// latituteField.setText("Location not available");
		// longitudeField.setText("Location not available");
		// }
	}

	/* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		// wl.acquire();
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				400, 1, this);
		Log.v("###", "onResume");
	}

	public void onDestroy() {
		super.onDestroy();
		// wl.release();
		Log.v("###", "onDestroy");
	}

	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		Log.v("###", "onPause");
		// wl.release();
		this.getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		locationManager.removeUpdates(this);
		super.onPause();
	}

	// @Override
	public void onLocationChanged(Location location) {
		String lat = String.valueOf(location.getLatitude());
		String lng = String.valueOf(location.getLongitude());
		String gpsspeed = String.valueOf(location.getSpeed());
		String accuracy = String.valueOf(location.getAccuracy());
		Log.e("GPS", "location changed: lat=" + lat + ", lng=" + lng);
		latituteField.setText(lat);
		longitudeField.setText(lng);
		GPSSpeedField.setText(gpsspeed);
		AccuracyField.setText(accuracy);

		//getOSMSpeed();

	}

	// @Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		Log.e("GPS", "status changed to " + provider + " [" + status + "]");

	}

	// @Override
	public void onProviderEnabled(String provider) {
		Toast.makeText(this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();

	}

	// @Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	// ----------------------------------------------
	
	
	private  class AndroidXMLParsingActivity extends AsyncTask<String, Void, String> {

		

		public String getXmlFromUrl(String url) {
			String xml = null;

			try {
				// defaultHttpClient
				Log.e("GPS", "in getXmlFromUrl 1...");
				DefaultHttpClient httpClient = new DefaultHttpClient();
				Log.e("GPS", "in getXmlFromUrl 2...");
				HttpPost httpPost = new HttpPost(url);
				Log.e("GPS", "in getXmlFromUrl 3...");
				
				//httpPost.setEntity(new UrlEncodedFormEntity(/*postParameters*/));
	            //Log.v("response code", response.getStatusLine().getStatusCode() + ""); 
				
				HttpResponse httpResponse = httpClient.execute(httpPost);
				Log.e("GPS", "in getXmlFromUrl 4...");
				HttpEntity httpEntity = httpResponse.getEntity();
				Log.e("GPS", "in getXmlFromUrl 5...");
				xml = EntityUtils.toString(httpEntity);
				Log.e("GPS", "in getXmlFromUrl 6...");
				

			} catch (UnsupportedEncodingException e) {
				Log.e("GPS", "in getXmlFromUrl 7...");
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				Log.e("GPS", "in getXmlFromUrl 8...");
				e.printStackTrace();
			} catch (MalformedURLException e) {
				Log.e("GPS", "in getXmlFromUrl 9...");
	        	e.printStackTrace();
	    	} catch (IOException e) {
	    		Log.e("GPS", "in getXmlFromUrl 10...");
				e.printStackTrace();
	    	} catch (Exception e) {
	    		Log.e("GPS", "in getXmlFromUrl 11...");
				e.printStackTrace();
			}
			
			// return XML
			return xml;
		}

		public Document getDomElement(String xml) {
			Document doc = null;
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			try {

				DocumentBuilder db = dbf.newDocumentBuilder();

				InputSource is = new InputSource();
				is.setCharacterStream(new StringReader(xml));
				doc = db.parse(is);

			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}
			// return DOM
			return doc;
		}

		public String getValue(Element item, String str) {
			NodeList n = item.getElementsByTagName(str);

			return this.getElementValue(n.item(0));
		}

		public final String getElementValue(Node elem) {
			Node child;
			if (elem != null) {
				if (elem.hasChildNodes()) {
					for (child = elem.getFirstChild(); child != null; child = child
							.getNextSibling()) {
						if (child.getNodeType() == Node.TEXT_NODE) {
							return child.getNodeValue();
						}
					}
				}
			}
			return "";
		}

		public final String getOSMSpeed() {
			final String URL = "http://nominatim.openstreetmap.org/reverse?lat=43.4618&lon=80.5311";
			// XML node keys
			final String KEY_ITEM = "result"; // parent node
			final String KEY_NAME = "osm_id";
			final String KEY_COST = "osm_id";
			final String KEY_DESC = "osm_id";

			Log.e("GPS", "getXmlFromUrl before...");
			String xml = getXmlFromUrl(URL); // getting XML
			Log.e("GPS", "getXmlFromUrl after...");
	/*
			Document doc = getDomElement(xml); // getting DOM element

			NodeList nl = doc.getElementsByTagName(KEY_ITEM);

			// looping through all item nodes <item>
			for (int i = 0; i < nl.getLength(); i++) {
				// HashMap<String, String> map = new HashMap<String, String>();
				Element e = (Element) nl.item(i);
				String name = getValue(e, KEY_NAME); // name child value
				String cost = getValue(e, KEY_COST); // cost child value
				String description = getValue(e, KEY_DESC); // description child
															// value

				Log.e("GPS", "in loop " + name + " - " + cost + " - " + description);

			}
	*/
			// Log.e("GPS", "after loop " + name + " - " + cost+ " - " +
			// description);
			return "";
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			Log.e("GPS", "in doInBackground 1...");
			getOSMSpeed();
			Log.e("GPS", "in doInBackground 2...");
			return null;
		}

		

		
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
}

